//
//  comBlueboxmoonPhoneWebABLookup.m
//  WebABLookup
//
//  Created by Daniel Hazelbaker on 10/2/12.
//  Copyright 2012 Blue Box Moon. All rights reserved.
//

#import "comBlueboxmoonPhoneWebABLookup.h"
#import "BMSnomPhone.h"
#import "BMJson.h"


@implementation comBlueboxmoonPhoneWebABLookup


//
// Set the default preferences.
//
+ (void)setDefaultPreferences
{
    BMPreferences *dict = [BMSnomPhone preferences];
    
    
    if ([dict valueForKey:kWebABURLKey] == nil)
        [dict setValue:@"" forKey:kWebABURLKey];
}


//
// Lookup the person record for the given phone numbers. The array is all
// possible phone numbers to look for. This lookup method only supports one
// phone number so only the first in the array is used.
//
- (NSDictionary *)lookupPersonForPhoneNumbers:(NSArray *)possiblePhoneNumbers
{
    NSMutableDictionary	*newPerson = [NSMutableDictionary dictionary];
    NSURLResponse       *response = nil;
    NSDictionary        *json;
    NSURLRequest        *request;
    NSData              *data;
    NSURL               *url;

    
    //
    // Make sure we are enabled.
    //
    if ([[[BMSnomPhone preferences] valueForKey:kWebABURLKey] length] == 0 || [[[BMSnomPhone preferences] valueForKey:kWebABEnabledKey] boolValue] == false)
        return nil;

    //
    // Make the web URL request to do the lookup.
    //
    url = [NSURL URLWithString:[NSString stringWithFormat:@"%@?number=%@", [[BMSnomPhone preferences] valueForKey:kWebABURLKey], [possiblePhoneNumbers objectAtIndex:0]]];
    request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:3.5];
    data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:NULL];
    if (data == nil) {
        NSLog(@"Could not request web address book data for call.");
        return nil;
    }
    if ([data length] == 0)
        return nil;

    //
    // Convert the results to json.
    //
    NS_DURING
    json = [BMJson decodeJson:[[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease]];
    NS_HANDLER
    json = nil;
    NS_ENDHANDLER
    if (json == nil) {
        NSLog(@"Got invalid response during web address book lookup: %@", [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease]);
        return nil;
    }
    [newPerson setValuesForKeysWithDictionary:json];

    //
    // If there is an image url then load it.
    //
    if ([[json valueForKey:@"imageURL"] length] != 0) {
        request = [NSURLRequest requestWithURL:[NSURL URLWithString:[json valueForKey:@"imageURL"]] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:2];
        data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:NULL];
        [newPerson setValue:data forKey:kPLImageData];
    }

    return newPerson;
}


@end
